using System;
using System.Windows.Forms;
using ICSharpCode.TextEditor.Document;
using ICSharpCode.TextEditor.Gui.CompletionWindow;

namespace ICSharpCode.TextEditor.Formatting.Intellisense
{
    public class DefaultCodeCompletionProvider : ICompletionDataProvider
    {
        private ImageList imageList;

        private ICompletionDataSupplier supplier = null;

        private int _defaultIndex = -1;

        public ImageList ImageList => imageList;

        public string PreSelection => null;

        public int DefaultIndex
        {
            get
            {
                return _defaultIndex;
            }
            private set
            {
                _defaultIndex = value;
            }
        }

        public DefaultCodeCompletionProvider(string fileExtension, ImageList imageList)
        {
            switch (fileExtension.ToUpper())
            {
                case "XML":
                    supplier = new XmlCompletionDataSupplier();
                    break;
                case "SQL":
                    supplier = new TsqlCompletionDataSupplier();
                    break;
                case "JavaScript":
                    supplier = new JavascriptCompletionDataSupplier();
                    break;
                case "JSON":
                    supplier = new JsonCompletionDataSupplier();
                    break;
            }
            this.imageList = imageList;
        }

        public CompletionDataProviderKeyResult ProcessKey(char key)
        {
            if (char.IsLetterOrDigit(key) || key == '_')
            {
                return CompletionDataProviderKeyResult.NormalKey;
            }
            return CompletionDataProviderKeyResult.InsertionKey;
        }

        public CompletionDataProviderKeyResult ProcessKey(TextEditorControl editor, char key)
        {
            if (char.IsLetterOrDigit(key) || key == '_')
            {
                return CompletionDataProviderKeyResult.NormalKey;
            }
            return CompletionDataProviderKeyResult.InsertionKey;
        }

        public bool InsertAction(ICompletionData data, TextArea textArea, int insertionOffset, char key)
        {
            textArea.Caret.Position = textArea.Document.OffsetToPosition(Math.Min(insertionOffset, textArea.Document.TextLength));
            return data.InsertAction(textArea, key);
        }

        public ICompletionData[] GenerateCompletionData(string fileName, TextArea textArea, char charTyped)
        {
            if (supplier == null)
            {
                return null;
            }
            int line = textArea.Caret.Line;
            LineSegment lineSegment = textArea.Document.GetLineSegment(line);
            return supplier.GetCompletionData(textArea.Document.GetText(lineSegment.Offset, textArea.Caret.Offset - lineSegment.Offset), charTyped);
        }
    }
}
